package it.univaq.mancoosi.injectors.systemconfiguration.managers;

import it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu.UbuntuEnvironmentManager;
import it.univaq.mancoosi.mancoosimm.File;
import it.univaq.mancoosi.mancoosimm.MancoosiFactory;
import it.univaq.mancoosi.mancoosimm.Module;
import it.univaq.mancoosi.mancoosimm.ModuleCache;
import it.univaq.mancoosi.mancoosimm.XFont;
import it.univaq.mancoosi.mancoosimm.XFontCache;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

public abstract class XFontCacheManager {
	protected static  XFontCacheManager INSTANCE ;	 
	protected MancoosiFactory factory; 
	private XFontCache xfontCache;
	protected HashMap<String, XFontCache> xfontCacheMap;
	protected HashMap<String, XFont> xfontMap;
	protected HashMap<String, File> filesMap;

	// Private constructor prevents instantiation from other classes
	protected XFontCacheManager() {
		factory = MancoosiFactory.eINSTANCE; 
		xfontCache = factory.createXFontCache();
		this.xfontCacheMap = new HashMap<String, XFontCache>();
		this.xfontMap = new HashMap<String, XFont>();
		this.filesMap = new HashMap<String, File>();
	}

	public static XFontCacheManager getInstance() {
		return INSTANCE;
	}

	public abstract void createXFontCachesFromSystem();

	public abstract void synchronize() throws IOException;	
	
	public abstract Boolean existsXFont(String xfontName);
	
	public abstract Boolean existsXFontCache(String xfontCacheName);
	
	public abstract Boolean existsFile(String fileName);
	
	public void syncMap () {
		Iterator<XFontCache> cacheIterator  = null;
		Iterator<XFont> xfontIterator  = null;
		Iterator<File> fileIterator = null;
		if(UbuntuEnvironmentManager.getInstance().getEnvironment().getXfontCaches() != null){
			cacheIterator = UbuntuEnvironmentManager.getInstance().getEnvironment().getXfontCaches().iterator();
		}
		if(cacheIterator != null){
			while (cacheIterator.hasNext()) {
				int indexCache = UbuntuEnvironmentManager.getInstance().getEnvironment().getXfontCaches().indexOf(cacheIterator.next());
				XFontCache xfc = UbuntuEnvironmentManager.getInstance().getEnvironment().getXfontCaches().get(indexCache);
				this.xfontCacheMap.put(xfc.getLocation(), xfc);
 				xfontIterator = xfc.getXfonts().iterator();
				if(xfontIterator != null){
					while (xfontIterator.hasNext()) {
						XFont curr = xfontIterator.next();
						this.xfontMap.put(curr.getName(), curr);
						fileIterator = curr.getFile().iterator();
						if(fileIterator != null){
							while (fileIterator.hasNext()) {
								File file = fileIterator.next();
								this.filesMap.put(file.getLocation(), file);
							}
						}
					}
				}
			}
		}
	}
}
